package it.gestionedocumentale.spring.service;

import it.gestionedocumentale.hibernate.dao.TagDAO;
import it.gestionedocumentale.hibernate.sessionfactory.HibernateSessionFactory;
import it.gestionedocumentale.model.Tag;
import it.gestionedocumentale.struts.form.TagForm;

import java.util.List;

import org.hibernate.Transaction;
import org.springframework.beans.BeanUtils;

public class TagServiceImpl implements TagService {

	private TagDAO tagDAO;

	public void setTagDAO(TagDAO tagDAO) {
		this.tagDAO = tagDAO;
	}

	public TagDAO getTagDAO() {
		return tagDAO;
	}

	@Override
	public void save(Tag transientInstance) throws Exception {
		Transaction tx = HibernateSessionFactory.getSession()
				.beginTransaction();
		tagDAO.save(transientInstance);
		tx.commit();

	}

	@Override
	public void delete(Tag persistentInstance) throws Exception {
		Transaction tx = HibernateSessionFactory.getSession()
				.beginTransaction();
		tagDAO.delete(persistentInstance);
		tx.commit();
	}

	@Override
	public void update(TagForm tagForm) throws Exception {
		Transaction tx = HibernateSessionFactory.getSession()
			.beginTransaction();
		Tag tagDaModificare = tagDAO.findById(tagForm.getIdTag());
		BeanUtils.copyProperties(tagForm, tagDaModificare);
		tx.commit();
	}
	
	@Override
	public Tag findById(Long idTag) throws Exception {
		Transaction tx = HibernateSessionFactory.getSession()
				.beginTransaction();
		Tag tag = tagDAO.findById(idTag);
		tx.commit();
		return tag;
	}

	@Override
	public List<Tag> findByExample(Tag instance) throws Exception {
		Transaction tx = HibernateSessionFactory.getSession()
				.beginTransaction();
		List<Tag> tags = tagDAO.findByExample(instance);
		tx.commit();
		return tags;
	}

	@Override
	public List<Tag> findAll() throws Exception {
		Transaction tx = HibernateSessionFactory.getSession()
				.beginTransaction();
		List<Tag> tags = tagDAO.findAll();
		tx.commit();
		return tags.size() < 1 ? null : tags;
	}

}
